package com.zp.business.impl.patPrepayment;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zp.base.api.RemoteSerialNumberUtils;
import com.zp.business.entity.patPrepayment.PatPrepayment;
import com.zp.business.entity.patPrepayment.bo.PatPrepaymentBo;
import com.zp.business.entity.patPrepayment.vo.PatPrepaymentVo;
import com.zp.business.mapper.patPrepayment.PatPrepaymentMapper;
import com.zp.business.service.patPrepayment.IPatPrepaymentService;
import com.zp.common.core.constant.BaseConstants;
import com.zp.common.core.utils.DateUtils;
import com.zp.common.core.utils.StringUtils;
import com.zp.common.myBatis.core.page.PageQuery;
import com.zp.common.myBatis.core.page.TableDataInfo;
import com.zp.common.satoken.utils.LoginHelper;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 患者住院预交金Service业务层处理
 *
 * @author zhang peng
 * @ date 2024-07-07
 */
@RequiredArgsConstructor
@Service
public class PatPrepaymentServiceImpl implements IPatPrepaymentService {

    private final PatPrepaymentMapper baseMapper;

    @DubboReference
    private RemoteSerialNumberUtils remoteSerialNumberUtils;

    /**
     * 查询患者住院预交金
     */
    @Override
    public PatPrepaymentVo queryById(String prepaymentId) {
        return baseMapper.selectVoById(prepaymentId);
    }

    /**
     * 查询患者住院预交金列表(分页)
     */
    @Override
    public TableDataInfo<PatPrepaymentVo> queryPageList(PatPrepaymentBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PatPrepayment> lqw = buildQueryWrapper(bo);
        Page<PatPrepaymentVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询患者住院预交金列表(不分页)
     */
    @Override
    public List<PatPrepaymentVo> queryList(PatPrepaymentBo bo) {
        LambdaQueryWrapper<PatPrepayment> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PatPrepayment> buildQueryWrapper(PatPrepaymentBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PatPrepayment> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getPatientId()), PatPrepayment::getPatientId, bo.getPatientId());
        lqw.eq(StringUtils.isNotBlank(bo.getVisitId()), PatPrepayment::getVisitId, bo.getVisitId());
        lqw.eq(StringUtils.isNotBlank(bo.getFeesNo()), PatPrepayment::getFeesNo, bo.getFeesNo());
        lqw.eq(StringUtils.isNotBlank(bo.getAcctNo()), PatPrepayment::getAcctNo, bo.getAcctNo());
        lqw.eq(bo.getAmountOfMoney() != null, PatPrepayment::getAmountOfMoney, bo.getAmountOfMoney());
        lqw.eq(StringUtils.isNotBlank(bo.getPayWay()), PatPrepayment::getPayWay, bo.getPayWay());
        lqw.eq(StringUtils.isNotBlank(bo.getCardNo()), PatPrepayment::getCardNo, bo.getCardNo());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), PatPrepayment::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getRefundedId()), PatPrepayment::getRefundedId, bo.getRefundedId());
        lqw.eq(StringUtils.isNotBlank(bo.getOrgId()), PatPrepayment::getOrgId, bo.getOrgId());
        lqw.eq(StringUtils.isNotBlank(bo.getRemarks()), PatPrepayment::getRemarks, bo.getRemarks());
        lqw.eq(bo.getPaymentAdvice() != null, PatPrepayment::getPaymentAdvice, bo.getPaymentAdvice());
        lqw.eq(StringUtils.isNotBlank(bo.getRefundedUser()), PatPrepayment::getRefundedUser, bo.getRefundedUser());
        lqw.orderByAsc(PatPrepayment::getCreateTime);
        return lqw;
    }

    /**
     * 新增患者住院预交金
     */
    @Override
    public Boolean insertByBo(PatPrepaymentBo bo) {
        PatPrepayment add = BeanUtil.toBean(bo, PatPrepayment.class);
        validEntityBeforeSave(add);
        add.initEntity();
        String prepaymentNo = remoteSerialNumberUtils.generatePrepaymentNo(bo.getOrgId());
        add.setFeesNo(prepaymentNo);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setPrepaymentId(add.getPrepaymentId());
        }
        return flag;
    }

    /**
     * 修改患者住院预交金
     */
    @Override
    public Boolean updateByBo(PatPrepaymentBo bo) {
        PatPrepayment update = BeanUtil.toBean(bo, PatPrepayment.class);
        update.updateInfo();
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PatPrepayment entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除患者住院预交金
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 预交金退费、作废
     */
    @Override
    @Transactional
    public Boolean refundApplication(String prepaymentId, String type) {
        PatPrepaymentVo patPrepaymentVo = baseMapper.selectVoById(prepaymentId);
        PatPrepaymentBo patPrepaymentBo = BeanUtil.toBean(patPrepaymentVo, PatPrepaymentBo.class);
        if (StringUtils.equals(type, BaseConstants.PAT_PREPAYMENT_TYPE.TWO)) {
            // 退费（增加新的负记录）
            String refundedId = "00" + patPrepaymentVo.getFeesNo();
            String prepaymentNo = remoteSerialNumberUtils.generatePrepaymentNo(patPrepaymentVo.getOrgId());
            PatPrepayment patNewPrepayment = new PatPrepayment();
            patNewPrepayment.setPatientId(patPrepaymentVo.getPatientId());
            patNewPrepayment.setVisitId(patPrepaymentVo.getVisitId());
            patNewPrepayment.setFeesNo(prepaymentNo);
            patNewPrepayment.setAmountOfMoney(BigDecimal.ZERO.subtract(patPrepaymentVo.getAmountOfMoney()));
            patNewPrepayment.setPayWay(patPrepaymentVo.getPayWay());
            patNewPrepayment.setOrgId(patPrepaymentVo.getOrgId());
            patNewPrepayment.setPrepaymentId("");
            patNewPrepayment.setType(BaseConstants.PAT_PREPAYMENT_TYPE.TWO);
            patNewPrepayment.initEntity();
            //新增负记录
            baseMapper.insert(patNewPrepayment);
            // 修改原纪录
            patPrepaymentBo.setRefundedId(prepaymentNo);
            patPrepaymentBo.setRefundedTime(DateUtils.getNowDate());
            patPrepaymentBo.setRefundedUser(LoginHelper.getLoginUser().getNickName());
        } else {
            // 作废（修改当前记录类型为作废）
            patPrepaymentBo.setType(BaseConstants.PAT_PREPAYMENT_TYPE.THREE);
        }
        patPrepaymentBo.updateEntity();
        return this.updateByBo(patPrepaymentBo);
    }
}
